package xq.gwt.mvc.model;

import java.io.Serializable;
import java.util.ArrayList;

public class PropertyModelList extends ArrayList<PropertyModel> implements PropertyChangedListener, Serializable{
	
	private static final long serialVersionUID = 7606509417175469196L;
	protected ArrayList<PropertyChangedListener> listeners = new ArrayList<PropertyChangedListener>();
	
	public void add(PropertyModel[] properties){
		if(properties == null)
			return;
		for (int i = 0; i < properties.length; i++) {
			add(properties[i]);
		}
	}
	
	public void remove(PropertyModel[] properties){
		if(properties == null)
			return;
		for (int i = 0; i < properties.length; i++) {
			remove(properties[i]);
		}
	}
	
	public boolean add(PropertyModel pm){
		boolean isAdded =  super.add(pm);
		if(isAdded)
			pm.addPropertyChangedListener(this);
		return isAdded;
	}

	public boolean remove(PropertyModel pm){
		boolean isRemoved =  super.remove(pm);
		if(isRemoved)
			pm.removePropertyChangedListener(this);
		return isRemoved;
	}
	
	public void propertyChanged(PropertyChangedEvent event) {
		for(PropertyChangedListener listener : listeners ){
			if(listener != null)
				listener.propertyChanged(event);
		}		
	}
	
	public boolean isValid(){		
		for(PropertyModel prop : this){
			if(!prop.isValid())
				return false;
		}		
		return true;
	}
	
	public boolean hasError(){		
		for(PropertyModel prop : this){
			if(!prop.getHasError())
				return false;
		}		
		return true;
	}
	
	public void addPropertyChangedListener(PropertyChangedListener listener){
		if(listener == null)
			return;
		listeners.add(listener);
	}
	
	public void removePropertyChangedListener(PropertyChangedListener listener){
		listeners.remove(listener);
	}

}
